package com.heima.search.service.impl;

import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.mapper.ApUserSearchMapper;
import com.heima.search.service.IApUserSearchService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * <p>
 * APP用户搜索信息表 服务实现类
 * </p>
 *
 * @author heima
 * @since 2021-03-27
 */
@Service
public class ApUserSearchServiceImpl extends ServiceImpl<ApUserSearchMapper, ApUserSearch> implements IApUserSearchService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private String PRE_FIX = "ld:search:word:";

    private String getRedisKey(Integer userId, UserSearchDto dto){
        String key="";
        if(userId!=null && userId!=0){
            key=PRE_FIX+userId;
        }else{
            key=PRE_FIX+dto.getEquipmentId();
        }
        return key;
    }

    @Override
    @Async("taskExecutor")
    public void saveSearchWords(Integer userId, UserSearchDto dto) {
        //设置key redis  1
        String key = getRedisKey(userId, dto);
        redisTemplate.opsForZSet().incrementScore(key,dto.getSearchWords(),1);
    }

    @Override
    public Set<String> loadSearchWords(UserSearchDto dto) {
        Integer userId = UserThreadLocalUtils.getUserId();
        String key = getRedisKey(userId, dto);
        //查询搜索记录   reverseRange 会根据得分降序查询
        Set<String> set = redisTemplate.opsForZSet().reverseRange(key, 0, 4);
        return set;
    }

    @Override
    public void delSearchWords(UserSearchDto dto) {
        Integer userId = UserThreadLocalUtils.getUserId();
        String key = getRedisKey(userId, dto);
        redisTemplate.opsForZSet().remove(key,dto.getSearchWords());
    }
}
